$(function () {
    obj.init();
});
var obj = new function () {
    'use strict';
    return {
        form:null,
        dataGrid:null,
        recordGrid:null,
        staffNumber:null,
        eastPanel:null,
        enableSeeRecord:true,
        oneSelectArr:[],
        eastPanelStatus:'close',
        init:function () {
            this.staffNumber = xhTool.getQuery('sStaffNumber');
            this.dataGrid = new xhDataGrid($('#detailList'),'hrm/attendance/getDetail',
                {
                    staffNumber:this.staffNumber,
                    startTime:xhTool.getQuery('startTime'),
                    endTime:xhTool.getQuery('endTime')
                });
            this.dataGrid.command({
                frozenColumns: [
                    [
                        {field:'ck',rowspan:2,width:30,checkbox:true},
                        {field:'iSAId',title:'iSAId',hidden:'true', rowspan:2,width:20},
                        {field:'bUnusual',title:'bUnusual',hidden:'true', rowspan:2,width:20},
                        {field:'bHoliday',title:'bHoliday',hidden:'true', rowspan:2,width:20},
                        {field:'sDay',title:'sDay',hidden:'true', rowspan:2,width:20},
                        {field:'sStaffNumber',title:'sStaffNumber', rowspan:2,hidden:'true',width:20},
                        {field:'dayStar',title:'#',align:'center', rowspan:2,halign:'center',width:'20px'},
                        {field:'sStaffName',title:'职工姓名', rowspan:2,align:'center',halign:'center',width:'80px;'},
                        {field:'sWeek',title:'日期', rowspan:2,align:'center',halign:'center',width:'150px'},
                        {field:'sAttendType',title:'考勤类型', rowspan:2,align:'center',halign:'center',width:'80px'},
                        {title:'上班打卡', colspan:2,align:'center',halign:'center'},
                        {title:'下班打卡', colspan:2,align:'center',halign:'center'},
                        {title:'时长（小时）', colspan:2,align:'center',halign:'center'}
                    ],
                    [
                        {field:'sSignIn',title:'打卡时间',align:'center',halign:'center',width:'140px'},
                        {field:'iLateType',title:'打卡状态',align:'center',halign:'center',width:'80px'},
                        {field:'sSignOut',title:'打卡时间',align:'center',halign:'center',width:'140px'},
                        {field:'iEarlyType',title:'打卡状态',align:'center',halign:'center',width:'80px'},
                        {field:'dWorkHour',title:'工作时长',align:'right',halign:'center',width:'80px'},
                        {field:'dOverHour',title:'加班时长',align:'right',halign:'center',width:'80px'}
                    ]
                ],
                columns:[
                    [
                        {field:'sCheckInfo',title:'审批信息', rowspan:2,align:'center',halign:'center',width:'250px'},
                        {title:'加班(天)', colspan:3,align:'center',halign:'center'},
                        {title:'迟到(次)', colspan:2,align:'center',halign:'center'},
                        {title:'早退(次)', colspan:2,align:'center',halign:'center'},
                        {title:'请假(天)', colspan:2,align:'center',halign:'center'},
                        {field:'dAbsent',title:'旷工(天)', rowspan:2,align:'center',halign:'center',width:'100px'},
                        {field:'iFixSign',title:'补卡(次)', rowspan:2,align:'center',halign:'center',width:'100px'}
                    ],
                    [
                        {field:'dOverTime',title:'延时',align:'right',halign:'center',width:'80px'},
                        {field:'dOverWeek',title:'周末',align:'right',halign:'center',width:'80px'},
                        {field:'iMeal',title:'餐补(次)',align:'right',halign:'center',width:'80px'},
                        {field:'late',title:'迟到',align:'right',halign:'center',width:'80px'},
                        {field:'veryLate',title:'严重迟到',align:'right',halign:'center',width:'80px'},
                        {field:'early',title:'早退',align:'right',halign:'center',width:'80px'},
                        {field:'veryEarly',title:'严重早退',align:'right',halign:'center',width:'80px'},
                        {field:'iOffType',title:'类型',align:'center',halign:'center',width:'80px'},
                        {field:'dOffDay',title:'时长',align:'right',halign:'center',width:'80px'}
                    ]
                ]
            });
            // this.dataGrid.command({
            //     columns:[
            //         [
            //             {field:'iSAId',title:'iSAId',hidden:'true', rowspan:2,width:20},
            //             {field:'bHoliday',title:'bHoliday',hidden:'true', rowspan:2,width:20},
            //             {field:'sDay',title:'sDay',hidden:'true', rowspan:2,width:20},
            //             {field:'sStaffNumber',title:'sStaffNumber', rowspan:2,hidden:'true',width:20},
            //             {field:'dayStar',title:'#',align:'center', rowspan:2,halign:'center',width:'20px'},
            //             {field:'sStaffName',title:'职工姓名', rowspan:2,align:'center',halign:'center',width:'80px;'},
            //             {field:'sWeek',title:'日期', rowspan:2,align:'center',halign:'center',width:'150px'},
            //             {field:'sAttendType',title:'考勤类型', rowspan:2,align:'center',halign:'center',width:'80px'},
            //             {title:'上班打卡', colspan:2,align:'center',halign:'center'},
            //             {title:'下班打卡', colspan:2,align:'center',halign:'center'},
            //             {field:'sCheckInfo',title:'审批信息', rowspan:2,align:'center',halign:'center',width:'80px'},
            //             {title:'加班(天)', colspan:3,align:'center',halign:'center'},
            //             {title:'迟到(次)', colspan:2,align:'center',halign:'center'},
            //             {title:'早退(次)', colspan:2,align:'center',halign:'center'},
            //             {title:'请假(天)', colspan:2,align:'center',halign:'center'},
            //             {field:'dAbsent',title:'旷工(天)', rowspan:2,align:'center',halign:'center',width:'100px'},
            //             {field:'iFixSign',title:'补卡(次)', rowspan:2,align:'center',halign:'center',width:'100px'}
            //         ],
            //         [
            //             {field:'sSignIn',title:'打卡时间',align:'center',halign:'center',width:'140px'},
            //             {field:'iLateType',title:'打卡状态',align:'center',halign:'center',width:'80px'},
            //             {field:'sSignOut',title:'打卡时间',align:'center',halign:'center',width:'140px'},
            //             {field:'iEarlyType',title:'打卡状态',align:'center',halign:'center',width:'80px'},
            //             {field:'dOverTime',title:'延时',align:'right',halign:'center',width:'80px'},
            //             {field:'dOverWeek',title:'周末',align:'right',halign:'center',width:'80px'},
            //             {field:'iMeal',title:'餐补(次)',align:'right',halign:'center',width:'80px'},
            //             {field:'late',title:'迟到',align:'right',halign:'center',width:'80px'},
            //             {field:'veryLate',title:'严重迟到',align:'right',halign:'center',width:'80px'},
            //             {field:'early',title:'早退',align:'right',halign:'center',width:'80px'},
            //             {field:'veryEarly',title:'严重早退',align:'right',halign:'center',width:'80px'},
            //             {field:'iOffType',title:'类型',align:'center',halign:'center',width:'80px'},
            //             {field:'dOffDay',title:'时长',align:'right',halign:'center',width:'80px'}
            //         ]
            //     ]
            // });
            this.dataGrid.parseToolbar().init().activeButton([],['bt_list_changeNormal','bt_list_changeOver','bt_list_signNormal']);

            //原始记录
            this.eastPanel = $('#eastPanel');
            this.recordGrid = new xhDataGrid($('#recordList'),'hrm/attendance/getRecord',{});
            this.recordGrid.parseToolbar().init().activeButton(['bt_list_fixSign']);
            this.recordGrid.command({
                title:false
            });
            this.listener();
            this.funObj().bindDgEvent();
            this.funObj().loadMenu();
        },
        listener:function () {
            var $this = this;
            //重新生成
            // $('#bt_list_generate').click(function () {
            //     if (xhExtra.buttonDisabled($(this))) {
            //         return false;
            //     }
            //     $this.funObj().generate();
            // });
            //查看每日记录
            // $('#bt_list_seeRecord').click(function () {
            //     if (xhExtra.buttonDisabled($(this))) {
            //         xhExtra.enableButton($(this), 'eu');
            //         $this.enableSeeRecord = true;
            //     } else  {
            //         $this.enableSeeRecord = false;
            //         xhExtra.disableButton($(this), 'eu');
            //     }
            // });

            //修改打卡时间
            $("#bt_list_fixSign").click(function () {
                if (xhExtra.buttonDisabled($(this))) {
                    return false;
                }
                $this.funObj().changeSign();
            });

            //设置为正常
            $('#bt_list_changeNormal').click(function () {
                if (xhExtra.buttonDisabled($(this))) {
                    return false;
                }
                $this.funObj().changeStatus(1);
            });

            //改变加班
            $('#bt_list_changeOver').click(function () {
                if (xhExtra.buttonDisabled($(this))) {
                    return false;
                }
                $this.funObj().changeOver();
            });

            //标记为正常
            $('#bt_list_signNormal').click(function () {
                if (xhExtra.buttonDisabled($(this))) {
                    return false;
                }
                $this.funObj().signNormal();
            });

            // //导入假期
            // $('#bt_list_import').click(function () {
            //     $this.funObj().importRecord();
            // });

            //搜索
            $('#bt_list_search').click(function () {
                $this.funObj().doSearch();
            });
            xhTool.bindDocKeyDown($('#bt_list_search'));
        },
        funObj:function () {
            var $this = this;
            return {
                doSearch:function () {
                    $this.dataGrid.reload({
                        key: xhExtra.getValue($('#list_search')),
                        startTime:xhExtra.getValue($('#List_Search_StartTime')),
                        endTime:xhExtra.getValue($('#List_Search_EndTime')),
                        staffNumber:$this.staffNumber,
                        offType:xhExtra.getValue($('#select_offType')),
                        lateType:xhExtra.getValue($('#select_lateType')),
                        earlyType:xhExtra.getValue($('#select_earlyType')),
                        overWork:xhExtra.getValue($('#select_overWork')),
                        holiday:xhExtra.getValue($('#select_holiday')),
                        unusual:xhExtra.getValue($('#select_unusual'))
                    })
                },
                bindDgEvent:function () {
                    $this.dataGrid.command({
                        rowStyler: function(index,row){
                            if (row.bUnusual == 1) {
                                return 'background-color:#CCCC66;';
                            }
                            if (row.bHoliday==1){
                                return 'background-color:#CCFFCC;'; // return inline style
                            }
                        }
                    });
                    $this.eastPanel.panel({
                        collapsed:true, //折叠
                        onCollapse:function () {
                            $this.eastPanelStatus = 'close';
                        },
                        onExpand:function () {
                            $this.eastPanelStatus = 'open';
                        }
                    });
                    // $this.dataGrid.onSelect = function (rowIndex, rowData) {
                    //
                    //     if ($this.dataGrid.command('getSelections').length == 1) {
                    //         $.each($this.oneSelectArr, function (_name, _value) {
                    //             xhExtra.enableButton($('#' + _value), 'eu');
                    //         });
                    //     } else {
                    //         $.each($this.oneSelectArr, function (_name, _value) {
                    //             xhExtra.disableButton($('#' + _value), 'eu');
                    //         });
                    //     }
                    // };
                    $this.dataGrid.onClickRow = function (rowIndex,rowData) {  //打开状态下 单机触发加载数据
                        if ($this.eastPanelStatus == 'open') {
                            $this.eastPanel.panel('setTitle', rowData['sStaffName']+'的打卡记录（' + rowData['sDay'] + '）');
                            $this.recordGrid.reload({
                                staffNumber:rowData['sStaffNumber'],
                                currentDay:rowData['sDay']
                            });
                        }
                    };
                    $this.dataGrid.onDblClickRow = function (rowIndex,rowData) { //双击展开右侧面板
                        if ($this.eastPanelStatus == 'close') {
                            var p = $("#mainLayout").layout("panel", "east")[0].clientWidth;
                            if (p <= 0) {
                                $('#mainLayout').layout('expand','east');

                            }
                        }
                        $this.eastPanel.panel('setTitle', rowData['sStaffName']+'的打卡记录（' + rowData['sDay'] + '）');
                        $this.recordGrid.reload({
                            staffNumber:rowData['sStaffNumber'],
                            currentDay:rowData['sDay']
                        });
                    };
                    // $this.dataGrid.onUnselect = function (rowIndex, rowData) {
                    //     // if ($this.enableSeeRecord) {
                    //     //     var p = $("#mainLayout").layout("panel", "east")[0].clientWidth;
                    //     //     if (p > 0) {
                    //     //         $('#mainLayout').layout('collapse','east');
                    //     //     }
                    //     // }
                    //     var length = $this.dataGrid.command('getSelections').length;
                    //     if (length == 1) {
                    //         $.each($this.oneSelectArr, function (_name, _value) {
                    //             xhExtra.enableButton($('#' + _value), 'eu');
                    //         });
                    //     }
                    //     else {
                    //         $.each($this.oneSelectArr, function (_name, _value) {
                    //             xhExtra.disableButton($('#' + _value), 'eu');
                    //         });
                    //     }
                    // };
                    $this.dataGrid.onLoadSuccess = function () {
                        $this.dataGrid.clear(); //清除选中
                    }
                },
                loadMenu:function () {
                    if ($('#bt_list_holidayMenu').length > 0 ) {
                        var $btn_menu=$('#bt_list_holidayMenu').menubutton({
                            iconCls: 'fa fa-pencil',
                            menu: '#mm'
                        });
                        $($btn_menu.menubutton('options').menu).menu({
                            onClick: function (item) {
                                //item 的相关属性参见API中的menu
                                var day = $this.dataGrid.getSelectValue('sDay');
                                var sStaffName = $this.dataGrid.getSelectValue('sStaffName');
                                var staffNumber = $this.dataGrid.getSelectValue('sStaffNumber');
                                if (!day) {
                                    window.top.xhTop.showError('请先选择一个日期');
                                    return false;
                                }
                                if (item.text == '设置为休息日') {
                                    xhExtra.askChangeStatus('hrm/attendance/changeHoliday',{bHoliday:2,day:day,staffNumber:staffNumber},$this.dataGrid, '确定要将'+sStaffName+day+'设为休息日么？',function (res) {
                                        window.top.xhTop.showSuccess(res.msg);
                                    });
                                } else if (item.text == '设置为工作日') {
                                    xhExtra.askChangeStatus('hrm/attendance/changeHoliday',{bHoliday:1,day:day,staffNumber:staffNumber},$this.dataGrid, '确定要将'+sStaffName+day+'设为工作日么？',function (res) {
                                        window.top.xhTop.showSuccess(res.msg);
                                    });
                                }
                            }
                        })
                    }
                },
                changeSign:function () {
                    var sDay = $this.recordGrid.getSelectValue('sDay');
                    var iSARId = $this.recordGrid.getSelectValue('iSARId');
                    window.top.swal({
                        title: '修改打卡记录',
                        confirmButtonText: '确定',
                        showCancelButton: true,
                        cancelButtonText: '取消',
                        showLoaderOnConfirm: true,
                        allowOutsideClick: false,
                        html: '<input id="day" class="form-control" placeholder="日期必填" type="date" value="'+sDay+'" />' +
                        '<select id="signType" class="swal2-select" style="width: 100%;">' +
                        '<option value="1" selected>上班打卡</option>' +
                        '<option value="2">下班打卡</option>' +
                        '</select>',
                        preConfirm: function() {
                            return new Promise(function (resolve, reject) {
                                var day = $('#day', window.top.document).val();
                                if (!day){
                                    reject('未填写日期！');
                                } else {
                                    resolve(day);
                                }
                            })
                        },
                        onOpen:function () {
                            var sAttendTime = $this.recordGrid.getSelectValue('sAttendTime');
                            if (sAttendTime) {
                                var time = sAttendTime.split(' ')[1];
                                if (time && time > '12:00') {
                                    $('#signType', window.top.document).val(2);
                                }
                            }
                        }
                    }).then(function (day) {
                        var signType   = $('#signType', window.top.document).val();
                        xhExtra.ajaxRequest('hrm/attendance/setUserAttendTime',{day:day,signType:signType,id:iSARId},{},function (res) {
                            window.top.xhTop.showSuccess(res.msg);
                            $this.dataGrid.reload();
                        })
                    },function (dismiss) {
                        return false;
                    });
                },
                changeStatus:function ($status) {
                    var str = '';
                    if ($status == 1) {
                        str = '正常';
                    }
                    var iSAId = $this.dataGrid.getSelectValue('iSAId');
                    if (!iSAId) {
                        window.top.xhTop.showError('错误','未选择记录');
                        return false;
                    }
                    window.top.swal({
                        title: '修改打卡状态为'+str,
                        confirmButtonText: '确定',
                        showCancelButton: true,
                        cancelButtonText: '取消',
                        showLoaderOnConfirm: true,
                        allowOutsideClick: false,
                        html: '<select id="attendType" class="swal2-select" style="width: 100%;">' +
                        '<option value="1" selected>上班</option>' +
                        '<option value="2">下班</option>' +
                        '</select>',
                        preConfirm: function() {
                            return new Promise(function (resolve, reject) {
                                var attendType = $('#attendType', window.top.document).val();
                                if (!attendType){
                                    reject('未选择上班或下班！');
                                } else {
                                    resolve(attendType);
                                }
                            })
                        }
                    }).then(function (attendType) {
                        xhExtra.ajaxRequest('hrm/attendance/dealStatus',{status:$status,attendType:attendType,id:iSAId},{},function (res) {
                            window.top.xhTop.showSuccess(res.msg);
                            $this.dataGrid.reload();
                        })
                    },function (dismiss) {
                        return false;
                    });
                },
                changeOver:function () {
                    var iSAId = $this.dataGrid.getSelectValue('iSAId');
                    if (!iSAId) {
                        window.top.xhTop.showError('错误','未选择记录');
                        return false;
                    }
                    window.top.swal({
                        title: '修改加班',
                        confirmButtonText: '确定',
                        showCancelButton: true,
                        cancelButtonText: '取消',
                        showLoaderOnConfirm: true,
                        allowOutsideClick: false,
                        html:
                        '<select id="overWeek" class="swal2-select" style="width: 100%;">' +
                            '<option value="0" selected>请选择</option>' +
                            '<option value="2" >周末全天</option>' +
                            '<option value="1">周末半天</option>' +
                        '</select>'+
                        '<select id="overWork" class="swal2-select" style="width: 100%;">' +
                            '<option value="0" selected>请选择</option>' +
                            '<option value="2" >延时两次</option>' +
                            '<option value="1">延时一次</option>' +
                        '</select>'
                        ,
                        preConfirm: function() {
                            return new Promise(function (resolve, reject) {
                                var overWeek = $('#overWeek', window.top.document).val();
                                var overWork = $('#overWork', window.top.document).val();
                                if (!overWeek || !overWork) {
                                    reject('请选择一个或两个加班类型！');
                                } else {
                                    resolve();
                                }
                            })
                        },
                        onOpen:function () {
                            var dOverTime = $this.dataGrid.getSelectValue('dOverTime');
                            var dOverWeek = $this.dataGrid.getSelectValue('dOverWeek');
                            if (dOverTime) {
                                $('#overWork', window.top.document).val(dOverTime*2);
                            }
                            if (dOverWeek) {
                                $('#overWeek', window.top.document).val(dOverWeek*2);
                            }
                        }
                    }).then(function () {
                        var overWeek = $('#overWeek', window.top.document).val();
                        var overWork = $('#overWork', window.top.document).val();
                        xhExtra.ajaxRequest('hrm/attendance/changeOver',{overWeek:overWeek,overWork:overWork,id:iSAId},{},function (res) {
                            window.top.xhTop.showSuccess(res.msg);
                            $this.dataGrid.reload();
                        })

                    },function (dismiss) {
                        return false;
                    });
                },
                signNormal:function () {
                    var iSAId = $this.dataGrid.getSelectValue('iSAId');
                    xhExtra.askChangeStatus('hrm/attendance/signNormal',{iSAId:iSAId},$this.dataGrid,'确定要将改记录标记为正常么',function (res) {
                        window.top.xhTop.showSuccess(res.msg);
                        $this.dataGrid.reload();
                    });
                }
                // generate:function () {
                //     var dayArr = $this.dataGrid.getSelectValues('sDay');
                //     var staffNumberArr = $this.dataGrid.getSelectValues('sStaffNumber');
                //     xhExtra.askChangeStatus('hrm/attendance/generateUserAttend',{staffNumberArr:staffNumberArr,dayArr:dayArr},$this.dataGrid,
                //         '确定要重新生成么?',function (res) {
                //             window.top.xhTop.showSuccess(res.msg);
                //         })
                //
                // },
                // importRecord:function () {
                //     window.top.swal({
                //         title: '导入excel文件',
                //         showCancelButton: true,
                //         cancelButtonText: '取消',
                //         showLoaderOnConfirm: true,
                //         allowOutsideClick: true,
                //         input: 'file',
                //         inputAttributes: {accept: '.xls,.xlsx'},
                //         confirmButtonText: '导入',
                //         preConfirm: function(file) {
                //             return new Promise(function (resolve, reject) {
                //                 if (!file) {
                //                     reject('文件不能为空！');
                //                 } else {
                //                     var fileData = new FormData();
                //                     fileData.append('file', file);
                //                     $.ajax({
                //                         url: baseUrl + 'hrm/attendance/importStaffDetail',
                //                         type: 'POST',
                //                         processData: false,
                //                         contentType: false,
                //                         data: fileData,
                //                         complete: function(XMLHttpRequest){
                //                             var result = XMLHttpRequest.responseJSON;
                //                             if(xhExtra.checkError(result)) return false;
                //                             window.top.xhTop.showSuccess(result.msg);
                //                             $this.dataGrid.reload();
                //                         }
                //                     });
                //                 }
                //             })
                //         }
                //     });
                // }
            }
        }
    }
};